package com.huanzhidadi.single.completablefuture;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class StockExecutorServiceTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CompletableFuture.supplyAsync(() -> {// 第一个任务
            return queryCode("中国石油");
        }, executorService).exceptionally(e -> {
            e.printStackTrace();
            return null;
        }).thenApplyAsync((code) -> {// 第二个任务
            if (StringUtils.isNotEmpty(code)) {
                return fetchPrice(code);
            } else {
                return null;
            }
        }, executorService).exceptionally(e -> {
            e.printStackTrace();
            return null;
        }).thenAcceptAsync((result) -> {
            if (null != result) {
                System.out.println("price: " + result);
            }
            executorService.shutdown();
        }, executorService);
        System.out.println("主线程结束");
    }

    static Double fetchPrice(String code) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        if (Math.random() < 0.3) {
            throw new RuntimeException("fetch price failed!");
        }
        return 5 + Math.random() * 20;
    }

    static String queryCode(String name) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        String code = "601857";
        if (!"中国石油".equals(name)) {
            throw new RuntimeException("编码查询异常!");
        } else {
            System.out.println(name + " 编码: " + code);
        }
        return code;
    }
}
